package com.swind.fast.modules.app.halali.partner.controller;

import java.util.Arrays;
import java.util.List;
import java.util.ArrayList;
import java.util.Map;
import java.util.stream.Collectors;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.swind.fast.common.api.vo.Result;
import com.swind.fast.common.system.query.QueryGenerator;
import com.swind.fast.common.util.oConvertUtils;
import com.swind.fast.common.constant.CommonConstant;
import com.swind.fast.modules.app.halali.partner.entity.Cart;
import com.swind.fast.modules.app.halali.partner.service.ICartService;
import com.swind.fast.modules.app.halali.partner.entity.Order;
import com.swind.fast.modules.app.halali.partner.service.IOrderService;

import com.swind.fast.modules.app.halali.partner.entity.OrderItem;
import com.swind.fast.modules.app.halali.partner.entity.RestaurantMeal;
import com.swind.fast.modules.app.halali.partner.service.IRestaurantMealService;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.extern.slf4j.Slf4j;

import org.jeecgframework.poi.excel.ExcelImportUtil;
import org.jeecgframework.poi.excel.def.NormalExcelConstants;
import org.jeecgframework.poi.excel.entity.ExportParams;
import org.jeecgframework.poi.excel.entity.ImportParams;
import org.jeecgframework.poi.excel.view.JeecgEntityExcelView;
import com.swind.fast.common.system.base.controller.SwindController;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.ModelAndView;
import com.alibaba.fastjson.JSON;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
// import com.swind.fast.common.aspect.annotation.AutoLog;

import com.swind.fast.modules.system.entity.SysAnnouncement;
import com.swind.fast.modules.system.entity.SysAnnouncementSend;
import com.swind.fast.modules.system.service.ISysAnnouncementSendService;
import com.swind.fast.modules.system.service.ISysAnnouncementService;
import java.util.Optional;
import java.text.DecimalFormat;
import com.swind.fast.modules.app.halali.partner.vo.response.CartPriceVo;

import org.springframework.web.servlet.mvc.method.annotation.SseEmitter;
import com.swind.fast.common.system.util.JwtUtil;
import com.swind.fast.modules.app.halali.partner.entity.HalaliPartner;
import com.swind.fast.modules.app.halali.partner.service.IHalaliPartnerService;
import io.swagger.annotations.ApiParam;
import org.springframework.http.MediaType;
import java.util.concurrent.ConcurrentHashMap;

 /**
 * @Description: 餐厅
 * @Author: swind
 * @Date:   2022-01-20
 * @Version: V1.0
 */
@Api(tags="00.商户端-SSE")
@RestController
@RequestMapping("/app/partner/sse")
@Slf4j
public class SseRestController {
	private static Map<String, SseEmitter> sseCache = new ConcurrentHashMap<>();

    @Autowired
    private IHalaliPartnerService halaliPartnerService;

    @ApiOperation(value="SSE-订阅", notes="")
	@ResponseBody
    @GetMapping(path = "/subscribe", produces = {MediaType.TEXT_EVENT_STREAM_VALUE})
    public SseEmitter pushAction(
            @ApiParam(name ="token",type="String",value="用户token",example="eyJ0eXAiO",required=true)
            @RequestParam(name="token", defaultValue="eyJ0eXAiO", required=true) String token
        ) throws IOException {
        String email = JwtUtil.getUsername(token);
        HalaliPartner sysUser = halaliPartnerService.getUserByEmail(email);
        if (oConvertUtils.isEmpty(sysUser)) {
            return null;
        }
        String userId = sysUser.getId();

        // 超时时间设置为1小时
        SseEmitter sseEmitter = new SseEmitter(3600_000L);
        sseCache.put(userId, sseEmitter);
        // 设置前端的重试时间为1s
        sseEmitter.send(SseEmitter.event().reconnectTime(1000).data("连接成功"));
        log.info("sse add userId : {}", userId);
        System.out.println("add " + userId);
        sseEmitter.onTimeout(() -> {
            log.info("sse timeout userId : {}", userId);
            sseCache.remove(userId);
        });
        sseEmitter.onCompletion(() -> log.info("sse onCompletion!"));
        return sseEmitter;
    }

    @ResponseBody
    @GetMapping(path = "/push")
    public String pushAction(@RequestParam(name="id", required=true) String id,
                             @RequestParam(name="orderId", required=true) String orderId) throws IOException {
        log.info("pushAction, id: {}, orderId: {}", id, orderId);
        SseEmitter sseEmitter = sseCache.get(id);

        if (sseEmitter != null) {
            sseEmitter.send(orderId);
        }
        return "over";
    }

    @ApiOperation(value="SSE-取消", notes="")
    @ResponseBody
    @GetMapping(path = "/cancel")
    public Result<?> cancelAction(@RequestParam(name="id", required=true) String id) {
        SseEmitter sseEmitter = sseCache.get(id);
        if (oConvertUtils.isNotEmpty(sseEmitter)) {
            sseEmitter.complete();
            sseCache.remove(id);
        }
        return Result.OK();
    }

}
